let $ = jQuery
//定义刷新数据源，根据最近一次筛选条件确定,默认为请求全数据的数据源
let dataSourceRequestTraceFlush = $('#dataSourceRequestAll').attr("action")
let dataSourceVisitTraceFlush = $('#dataSourceVisitAll').attr("action")

//存放了显示各种图表的方法
let myChart = {
    totalLogs:0,

    //普通线性表数据处理
    //返回二元数组
    //第一元为名称序列
    //第二元为数据序列
    lineChartDataPrePrecess:function(primitiveData){
        console.log("原始数据")
        console.log(primitiveData)
        let DataArray = [[],[]]
        for(let key in primitiveData){
            DataArray[0].push(key)
            DataArray[1].push(primitiveData[key])
        }
        console.log("排序前"+DataArray)
        //根据日期重新排序
        //冒泡排序
        console.log("数组长"+DataArray[0].length)
        for(let i=0; i<DataArray[0].length-1; i++){
            //每一轮比较要比多少次
            for(let j=0; j<DataArray[0].length-1-i; j++){
                //如果第一个比第二个大，就交换他们两个位置
                let date1String =DataArray[0][j]
                let date2String =DataArray[0][j+1]
                let date1 = new Date(Date.parse(date1String.replace(/-/g, '/')))
                let date2 = new Date(Date.parse(date2String.replace(/-/g, '/')))
                if(date1>date2){
                    let tempDate = DataArray[0][j];
                    DataArray[0][j] = DataArray[0][j+1];
                    DataArray[0][j+1] = tempDate;
                    let tempCount =DataArray[1][j]
                    DataArray[1][j] = DataArray[1][j+1];
                    DataArray[1][j+1] = tempCount;
                }
            }
        }

        console.log("排序后"+DataArray)
        return DataArray
    },

    //普通线性表显示
    lineChartShow:function (elementId,dataNameSeries,dataSeries,title) {
        let chartDom =  document.getElementById(elementId);
        let chart = echarts.init(chartDom);
        let option;

        if(dataNameSeries.length !== dataSeries.length){
            layer.msg('数据名和数据无法一一对应!',null)
        }else{
            option = {
                title: {
                    left: 'center',
                    text: title
                },
                //鼠标提示标语
                tooltip: {
                    trigger: 'axis',
                    position: function (pt) {
                        return [pt[0], '10%'];
                    }
                },
                //右上角工具箱
                toolbox: {
                    feature: {
                        dataView:{
                          show:true,
                          title:'数据视图'
                        },
                        saveAsImage: {
                            title:'导出成图片'
                        },
                        magicType: {
                            type: ['line', 'bar'],//启用与线性表兼容的动态图表
                            title:{
                                line:'切换为折线图',
                                bar:'切换为柱状图'
                            }
                        }
                    }
                },
                //x轴属性
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: dataNameSeries
                },
                //y轴属性
                yAxis: {
                    type: 'value'
                },
                //区域缩放组件
                //
                dataZoom: [
                    {
                        type: 'inside',
                        start: 0,
                        end: 100
                    },
                    {
                        start:0,
                        end: 0
                    }
                ],
                //数据序列
                //data是数据接口
                series: [
                    {
                        name: '访问次数',
                        data: dataSeries,
                        type: 'line',
                        symbol: 'none',
                        sampling: 'lttb',
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {
                                    offset: 0,
                                    color: 'rgb(255, 158, 68)'
                                },
                                {
                                    offset: 1,
                                    color: 'rgb(255, 70, 131)'
                                }
                            ])
                        }
                    }
                ]
            };

            option && chart.setOption(option);
        }

    },

    effectiveDataCalculate:function (DataArray){
        this.totalLogs =0
        for(let i=0;i<DataArray.length;i++){
            this.totalLogs += DataArray[i]
        }
    }

}





//-------------------------------------------------网站请求量统计--------------------------------------------------------------------

//筛选条件菜单
layui.use('dropdown', function(){
    let dropdown = layui.dropdown
    dropdown.render({
        elem: '#optionMenu' //可绑定在任意元素中，此处以上述按钮为例
        ,data: [{
            title: '自网站开启'
            ,id: 0
        },{
            title: '近一个星期'
            ,id: 1
        },{
            title: '近一个月'
            ,id: 2
        },{
            title: '指定日期范围'
            ,id: 3
        }]
        ,id: 'optionMenu'
        //菜单被点击的事件
        ,click: function(obj){
            console.log(obj);
           if(obj.id === 0){
               $.getJSON(
                   $('#dataSourceRequestAll').attr("action"),
                   null,
                   function (json) {
                       let dataArray = myChart.lineChartDataPrePrecess(json)
                       myChart.lineChartShow('chart',dataArray[0],dataArray[1],"网站请求次数总计")
                       myChart.effectiveDataCalculate(dataArray[1])
                       requestVue.$data.total = myChart.totalLogs//设置网站总请求量的数据标题
                       dataSourceRequestTraceFlush = $('#dataSourceRequestAll').attr("action")
                   }

               )
           }else if(obj.id === 1) {
               $.getJSON(
                   $('#dataSourceRequestWeek').attr("action"),
                   null,
                   function (json) {
                       let dataArray = myChart.lineChartDataPrePrecess(json)
                       myChart.lineChartShow('chart',dataArray[0],dataArray[1],"近一个星期网站请求统计")
                       dataSourceRequestTraceFlush = $('#dataSourceRequestWeek').attr("action")
                       myChart.effectiveDataCalculate(dataArray[1])
                       requestVue.$data.total = myChart.totalLogs//设置网站总请求量的数据标题
                   }

               )
           }else if(obj.id ===2){
               $.getJSON(
                   $('#dataSourceRequestMonth').attr("action"),
                   null,
                   function (json) {
                       let dataArray = myChart.lineChartDataPrePrecess(json)
                       myChart.lineChartShow('chart',dataArray[0],dataArray[1],"近一个月网站请求统计")
                       dataSourceRequestTraceFlush = $('#dataSourceRequestMonth').attr("action")
                       myChart.effectiveDataCalculate(dataArray[1])
                       requestVue.$data.total = myChart.totalLogs//设置网站总请求量的数据标题
                   }

               )
           }else if(obj.id ===3){
               layer.open({
                   type:1,
                   title: '指定统计的日期范围',
                   content: $('#openRequestDateTraceProductBox'),//利用jQuery嵌入弹出层容器
                   area:['430px','270px'],
                   end:function (){
                       $('#openRequestDateTraceProductBox').hide()
                   }
               })

           }
        }
    });
});

//用于动态数据显示网站总请求量的Vue
let requestVue = new Vue({
    el:'#requestTrace',
    data:{
        total:0,
    }
})

//负责设置日期范围的方法
layui.use('laydate',function (){
    let laydate = layui.laydate;
    laydate.render({
        elem:'#requestDateRange',
        range:['#requestStartDate','#requestEndDate'],
        done:function (value,date,endDate) {
            let start = JSON.parse(JSON.stringify(date))
            let end = JSON.parse(JSON.stringify(endDate))
            if(!(value === '' || value === undefined || value === null)){
                requestDateSelectVue.$data.startDate = start.year+'-'+start.month+'-'+start.date
                requestDateSelectVue.$data.endDate =  end.year+'-'+end.month+'-'+end.date

            }else{
                requestDateSelectVue.$data.startDate  = ''
                requestDateSelectVue.$data.endDate =  ''
            }

        }
    })
})

//用于提交按日期范围统计请求的Vue
let requestDateSelectVue = new Vue({
    el:'#requestDateTrace',
    data:{
        startDate:'',
        endDate:''
    },
    methods:{
        requestDateSubmit:function (event){
            if(this.startDate === '' || this.endDate === ''){
                layer.msg('请选择日期',{
                    time:1500
                })
            }else{
                axios({
                    url:$('#dataSourceRequestDateRange').attr("action"),
                    method:'post',
                    data:{
                        selectInfo:{
                            startDate:this.startDate,
                            endDate:this.endDate
                        }
                    }
                }).then(function (response) {
                    let data = JSON.parse(JSON.stringify(response.data))
                    let dataArray = myChart.lineChartDataPrePrecess(data)
                    myChart.lineChartShow('chart',dataArray[0],dataArray[1],requestDateSelectVue.$data.startDate+"到"+requestDateSelectVue.$data.endDate+"间的访问量统计")
                    myChart.effectiveDataCalculate(dataArray[1])
                    requestVue.$data.total = myChart.totalLogs//设置网站总请求量的数据标题
                    requestDateSelectVue.$data.startDate = ''
                    requestDateSelectVue.$data.endDate = ''
                    layer.closeAll()
                })
            }
        }
    }
})

//------------------------------------------------------授权用户统计-----------------------------------------------------------------
//用于动态数据显示网站总请求量的Vue
let visitVue = new Vue({
    el:'#visitTrace',
    data:{
        total:0,
    }
})


//筛选条件菜单
layui.use('dropdown', function(){
    let dropdown = layui.dropdown
    dropdown.render({
        elem: '#optionMenu2' //可绑定在任意元素中，此处以上述按钮为例
        ,data: [{
            title: '自网站开启'
            ,id: 0
        },{
            title: '近一个星期'
            ,id: 1
        },{
            title: '近一个月'
            ,id: 2
        },{
            title: '指定日期范围'
            ,id: 3
        }]
        ,id: 'optionMenu2'
        //菜单被点击的事件
        ,click: function(obj){
            console.log(obj);
            if(obj.id === 0){
                $.getJSON(
                    $('#dataSourceVisitAll').attr("action"),
                    null,
                    function (json) {
                        let dataArray = myChart.lineChartDataPrePrecess(json)
                        myChart.lineChartShow('chart2',dataArray[0],dataArray[1],"网站访问次数总计")
                        myChart.effectiveDataCalculate(dataArray[1])
                        requestVue.$data.total = myChart.totalLogs//设置网站总请求量的数据标题
                        dataSourceRequestTraceFlush = $('#dataSourceVisitAll').attr("action")
                    }

                )
            }else if(obj.id === 1) {
                $.getJSON(
                    $('#dataSourceVisitWeek').attr("action"),
                    null,
                    function (json) {
                        let dataArray = myChart.lineChartDataPrePrecess(json)
                        myChart.lineChartShow('chart2',dataArray[0],dataArray[1],"近一个星期网站访问统计")
                        dataSourceRequestTraceFlush = $('#dataSourceVisitWeek').attr("action")
                        myChart.effectiveDataCalculate(dataArray[1])
                        requestVue.$data.total = myChart.totalLogs//设置网站总请求量的数据标题
                    }

                )
            }else if(obj.id ===2){
                $.getJSON(
                    $('#dataSourceVisitMonth').attr("action"),
                    null,
                    function (json) {
                        let dataArray = myChart.lineChartDataPrePrecess(json)
                        myChart.lineChartShow('chart2',dataArray[0],dataArray[1],"近一个月网站访问统计")
                        dataSourceRequestTraceFlush = $('#dataSourceVisitMonth').attr("action")
                        myChart.effectiveDataCalculate(dataArray[1])
                        requestVue.$data.total = myChart.totalLogs//设置网站总请求量的数据标题
                    }

                )
            }else if(obj.id ===3){
                layer.open({
                    type:1,
                    title: '指定统计的日期范围',
                    content: $('#openVisitDateTraceProductBox'),//利用jQuery嵌入弹出层容器
                    area:['430px','270px'],
                    end:function (){
                        $('#openVisitDateTraceProductBox').hide()
                    }
                })

            }
        }
    });
});

//负责设置日期范围的方法
layui.use('laydate',function (){
    let laydate = layui.laydate;
    laydate.render({
        elem:'#visitDateRange',
        range:['#visitStartDate','#visitEndDate'],
        done:function (value,date,endDate) {
            let start = JSON.parse(JSON.stringify(date))
            let end = JSON.parse(JSON.stringify(endDate))
            if(!(value === '' || value === undefined || value === null)){
                visitDateSelectVue.$data.startDate = start.year+'-'+start.month+'-'+start.date
                visitDateSelectVue.$data.endDate =  end.year+'-'+end.month+'-'+end.date

            }else{
                visitDateSelectVue.$data.startDate  = ''
                visitDateSelectVue.$data.endDate =  ''
            }

        }
    })
})

//用于提交按日期范围统计请求的Vue
let visitDateSelectVue = new Vue({
    el:'#visitDateTrace',
    data:{
        startDate:'',
        endDate:''
    },
    methods:{
        visitDateSubmit:function (event){
            if(this.startDate === '' || this.endDate === ''){
                layer.msg('请选择日期',{
                    time:1500
                })
            }else{
                axios({
                    url:$('#dataSourceVisitDateRange').attr("action"),
                    method:'post',
                    data:{
                        selectInfo:{
                            startDate:this.startDate,
                            endDate:this.endDate
                        }
                    }
                }).then(function (response) {
                    let data = JSON.parse(JSON.stringify(response.data))
                    let dataArray = myChart.lineChartDataPrePrecess(data)
                    myChart.lineChartShow('chart2',dataArray[0],dataArray[1],visitDateSelectVue.$data.startDate+"到"+visitDateSelectVue.$data.endDate+"间的访问量统计")
                    myChart.effectiveDataCalculate(dataArray[1])
                    visitVue.$data.total = myChart.totalLogs//设置网站总请求量的数据标题
                    visitDateSelectVue.$data.startDate = ''
                    visitDateSelectVue.$data.endDate = ''
                    layer.closeAll()
                })
            }
        }
    }
})









//用于跳转sentinel控制台的vue
let visitSentinelVue = new Vue({
    el:'#toSentinel',
    data:{
        hostname: '',
        port: 4081,

    },
    methods:{
        redirect:function (event){
            // window.location.href="http://192.168.0.21:3081/#/login"
            if(this.hostname === '' ) {
                layer.msg('请输入主机名', {
                    time: 1500
                })
            }else if(isNaN(this.port)){
                layer.msg('请输入端口号', {
                    time: 1500
                })

            } else{
                let url =  'http://' + this.hostname + ":" + this.port
                $.ajax({
                    type:"get",
                    url:url,
                    timeout:1000,
                    success: function (){
                        window.location.href=url
                    },
                    error:function (xhr,status,error){
                        layer.msg("错误信息："+error, {
                            time: 1500
                        })
                    }
                })


            }
        }
    }
})


//jQuery事件，用于处理单独的echart事件或者某些不涉及到返回数据处理的事件

//页面加载完成后的初始echart事件，即统计所有访问记录
$(document).ready(function (){
    $.getJSON(
        dataSourceRequestTraceFlush,
        null,
       function (json) {
           let dataArray = myChart.lineChartDataPrePrecess(json)
           myChart.lineChartShow('chart',dataArray[0],dataArray[1],"网站请求次数总计")
           myChart.effectiveDataCalculate(dataArray[1])
           requestVue.$data.total = myChart.totalLogs//设置网站总请求量的数据标题
       }

    )

    $.getJSON(
        dataSourceVisitTraceFlush,
        null,
        function (json) {
            let dataArray = myChart.lineChartDataPrePrecess(json)
            myChart.lineChartShow('chart2',dataArray[0],dataArray[1],"网站访问次数总计")
            myChart.effectiveDataCalculate(dataArray[1])
            visitVue.$data.total = myChart.totalLogs//设置网站总请求量的数据标题
        }

    )

    //选择取消按钮
    $('#requestDateCancel').click(function (){
        layer.closeAll()
    })

    $('#visitDateCancel').click(function (){
        layer.closeAll()
    })

    //跳转流量控制界面
    $('#redirectCancel').click(function (){
        visitSentinelVue.$data.port = 4081
        visitSentinelVue.$data.hostname = ''
    })


})

